﻿
@{
    ViewBag.Title = "App";
}
<div style="width:100%;height:100%">
    <div class="panel-body" style="padding-bottom:0px;">
        <div class="panel panel-default">
            <div class="panel-heading">查询条件</div>
            <div class="panel-body">
                <form id="formSearch" class="form-horizontal">
                    <div class="form-group" style="margin-top:15px">
                        <label class="control-label col-sm-1" for="txt_app_Name">应用名</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="txt_app_Name">
                        </div>
                        <div class="col-sm-4" style="text-align:left;">
                            <button type="button" style="margin-left:50px" id="btn_query" class="btn btn-primary">查询</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <div id="toolbar" class="btn-group">
            <button id="btn_add" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
            </button>
            <button id="btn_edit" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
            </button>
            <button id="btn_delete" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
            </button>
        </div>
        <table id="tb_apps" style="height:15%"></table>
    </div>
</div>
<form id="edit-form" class="form-inline">
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document" style="width:65%">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">新增</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="txt_appID">应用ID</label>
                        <input type="text" name="txt_appID" class="form-control has-feedback" id="txt_appID" placeholder="自动生成" disabled>
                    </div>
                    <div class="form-group">
                        <label for="txt_appName">应用名称</label>
                        <input type="text" name="txt_appName" class="form-control" id="txt_appName" placeholder="应用名称">
                    </div>
                    <div class="form-group">
                        <label for="txt_clientSecret">秘钥</label>
                        <input type="text" name="txt_clientSecret" class="form-control" id="txt_clientSecret" placeholder="秘钥">
                    </div>
                    <div class="form-group">
                        <label for="txt_returnUrl">应用地址</label>
                        <input type="text" name="txt_returnUrl" class="form-control" id="txt_returnUrl" placeholder="应用地址">
                    </div>
                    <div class="form-group">
                        <label> 是否可信</label>
                        <div class="checkbox">
                            <label>
                                <input id="ckb_isCredible" type="checkbox">
                            </label>
                        </div>
                    </div>
                    <div class="form-group" style="display:block">
                        <label for="txt_iconUrl"> 应用图标</label>
                        <div style="display:inline-block">
                            <input type="text" name="txt_iconUrl" class="form-control" id="txt_iconUrl" placeholder="图标" style="display:none">
                            <input type="file" name="file_iconUrl" class="file-loading" id="file_iconUrl" />
                        </div>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭</button>
                    <button type="submit" id="btn_submit" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span>保存</button>
                </div>
            </div>
        </div>
    </div>
</form>
<style>
    .form-group {
        padding: 3px;
    }

        .form-group > label {
            width: 85px;
            text-align: right;
        }

        .form-group > input {
            padding-right: 42.5px;
        }

    .panel {
        margin-bottom: 5px;
    }

    .panel-body {
        padding: 5px;
    }
</style>
@section scripts
{
    <script type="text/javascript">
        $(function () {

            //1.初始化Table
            var oTable = new TableInit();
            oTable.Init();

            //2.初始化Button的点击事件
            var oButtonInit = new ButtonInit();

            oButtonInit.Init();

            InitForm();

            var oFileInput = new FileInput();
            oFileInput.Init("file_iconUrl", "/App/ImportIconImage");
        });

        var TableInit = function () {
            var oTableInit = new Object();
            //初始化Table
            oTableInit.Init = function () {
                function iconUrlFormatter(value) {
                    if (value) {
                        var imageurl = ImageBaseUrl + value;
                        return "<img src='" + imageurl + "' height='32' width='32' class='file-preview-image' alt='应用图片' title='应用图片'>";
                    }
                    return value;
                };
                $('#tb_apps').bootstrapTable({
                    url: '/App/Query', //请求后台的URL（*）
                    method: 'post',  //请求方式（*）
                    toolbar: '#toolbar', //工具按钮用哪个容器
                    striped: true,  //是否显示行间隔色
                    cache: false,  //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                    pagination: true,  //是否显示分页（*）
                    sortable: false,  //是否启用排序
                    sortOrder: "asc",  //排序方式
                    queryParams: oTableInit.queryParams,//传递参数（*）
                    responseHandler: function (res) { return res.Data; },
                    sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
                    pageNumber: 1,  //初始化加载第一页，默认第一页
                    pageSize: 10,  //每页的记录行数（*）
                    pageList: [5, 10, 25, 50, 100], //可供选择的每页的行数（*）
                    strictSearch: true,
                    showColumns: true,  //是否显示所有的列
                    showRefresh: true,  //是否显示刷新按钮
                    minimumCountColumns: 2, //最少允许的列数
                    clickToSelect: true, //是否启用点击选中行
                    height: 400,  //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                    uniqueId: "ID",  //每一行的唯一标识，一般为主键列
                    showToggle: true,  //是否显示详细视图和列表视图的切换按钮
                    cardView: false,  //是否显示详细视图
                    detailView: false,  //是否显示父子表
                    columns: [{
                        checkbox: true
                    }, {
                        field: 'ClientID',
                        title: '应用ID'
                    }, {
                        field: 'Name',
                        title: '应用名称'
                    }, {
                        field: 'ClientSecret',
                        title: '秘钥'
                    }, {
                        field: 'ReturnUrl',
                        title: '应用地址'
                    }, {
                        field: 'IsCredible',
                        title: '可信'
                    }, {
                        formatter: iconUrlFormatter,
                        field: 'IconUrl',
                        title: '图标'
                    }, {
                        field: 'CreatedOn',
                        title: '创建时间'
                    }, {
                        field: 'CreatedBy',
                        title: '创建人'
                    }, {
                        field: 'LastUpdatedOn',
                        title: '最后更新时间'
                    }, {
                        field: 'LastUpdatedBy',
                        title: '最后更新人'
                    }]
                });
            };
            //得到查询的参数
            oTableInit.queryParams = function (params) {
                var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                    Limit: params.limit, //页面大小
                    Offset: (params.offset), //页码
                    Name: $("#txt_app_Name").val()
                };
                return temp;
            };
            return oTableInit;
        };

        var ButtonInit = function () {
            var oInit = new Object();
            oInit.Init = function () {
                //新增数据click事件注册
                $("#btn_add").click(function () {
                    $("#myModalLabel").text("新增");
                    $("#myModal").find(".form-control").val("");
                    $("#ckb_isCredible").prop("checked", false);
                    InitForm({ isCreate: true, ID: '' });
                    $('#file_iconUrl').fileinput('clear');
                    $('#myModal').modal();
                });

                //编辑数据click事件注册
                $("#btn_edit").click(function () {
                    var arrselections = $("#tb_apps").bootstrapTable('getSelections');
                    if (arrselections.length > 1) {
                        toastr.warning('只能选择一行进行编辑');
                        return;
                    }
                    if (arrselections.length <= 0) {
                        toastr.warning('请选择有效数据');
                        return;
                    }
                    $("#myModalLabel").text("编辑");
                    $("#txt_appID").val(arrselections[0].ClientID);
                    $("#txt_appName").val(arrselections[0].Name);
                    $("#txt_clientSecret").val(arrselections[0].ClientSecret);
                    $("#txt_returnUrl").val(arrselections[0].ReturnUrl);
                    $("#txt_iconUrl").val(arrselections[0].IconUrl);
                    $("#ckb_isCredible").prop("checked", arrselections[0].IsCredible);
                    InitForm({ isCreate: false, ID: arrselections[0].ID });
                    $('#file_iconUrl').fileinput('clear');
                    if (arrselections[0].IconUrl && arrselections[0].IconUrl.length > 3) {
                        var control = $("#file_iconUrl");
                        var imageurl = ImageBaseUrl + arrselections[0].IconUrl;
                        //重要，需要更新控件的附加参数内容，以及图片初始化显示
                        control.fileinput('refresh', {
                            uploadExtraData: { ID: arrselections[0].ID },
                            initialPreview: [ //预览图片的设置
                                "<img src='" + imageurl + "' class='file-preview-image' alt='应用图片' title='应用图片'>",
                            ],
                        });
                    }
                    $('#myModal').modal();

                });

                //删除数据click事件注册
                $("#btn_delete").click(function () {
                    var arrselections = $("#tb_apps").bootstrapTable('getSelections');
                    if (arrselections.length <= 0) {
                        toastr.warning('请选择有效数据');
                        return;
                    }
                    Ewin.confirm({ message: "确认要删除选择的数据吗？" }).on(function (e) {
                        if (!e) {
                            return;
                        }
                        $.ajax({
                            type: "post",
                            url: "/App/Delete",
                            data: { ids: $.Enumerable.From(arrselections).Select('$.ID').ToArray() },
                            success: function (data, status) {
                                if (status == "success") {
                                    toastr.success('提交数据成功');
                                    $("#tb_apps").bootstrapTable('refresh');
                                }
                            },
                            dataType: "json",
                            error: function () {
                                toastr.error('Error');
                            },
                            complete: function () {

                            }

                        });
                    });
                });

                //条件查询click事件注册
                $("#btn_query").click(function () {
                    $("#tb_apps").bootstrapTable('refresh');
                });
            };
            return oInit;
        };

        var isCreate, postdata = {};

        var InitForm = function (args) {
            var editForm = $("#edit-form").data('bootstrapValidator');
            if (editForm) {
                isCreate = args.isCreate;
                postdata.ID = args.ID;
                editForm.resetForm();
                return;
            }
            $('#edit-form').bootstrapValidator({
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                submitHandler: function (validator, form, submitButton) {
                    postdata.Name = $("#txt_appName").val();
                    postdata.ClientSecret = $("#txt_clientSecret").val();
                    postdata.ReturnUrl = $("#txt_returnUrl").val();
                    postdata.IsCredible = $("#ckb_isCredible").prop("checked");
                    postdata.IconUrl = $("#txt_iconUrl").val();
                    $.ajax({
                        type: "post",
                        url: isCreate ? "/App/Create" : "/App/Edit",
                        data: postdata,
                        //contentType: "application/json; charset=utf-8",
                        //dataType: "json",
                        success: function (data, status) {
                            if (status == "success") {
                                toastr.success('提交数据成功');
                                $('#myModal').modal('hide');
                                $("#tb_apps").bootstrapTable('refresh');
                            }
                        },
                        error: function () {
                            toastr.error('Error');
                        },
                        complete: function () {

                        }

                    });
                },
                fields: {
                    txt_appName: {
                        validators: {
                            notEmpty: {
                                message: 'The app name is required'
                            }
                        }
                    },
                    txt_clientSecret: {
                        validators: {
                            notEmpty: {
                                message: 'The client secret is required'
                            }
                        }
                    }
                    //,txt_returnUrl: {
                    //    validators: {
                    //        notEmpty: {
                    //            message: 'The returnUrl is required'
                    //        },
                    //        uri: {
                    //            message: 'The returnUrl is uri'
                    //        }
                    //    }
                    //}
                }
            });
        }

        //初始化fileinput
        var FileInput = function () {
            var oFile = new Object();
            //初始化fileinput控件（第一次初始化）
            oFile.Init = function (ctrlName, uploadUrl) {
                var control = $('#' + ctrlName);

                //初始化上传控件的样式
                control.fileinput({
                    language: 'zh', //设置语言
                    uploadUrl: uploadUrl, //上传的地址
                    allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀
                    showCaption: false,//是否显示标题
                    zoomModalHeight: 220,
                    maxFileCount: 1,
                    dropZoneEnabled: false//是否显示拖拽区域
                    //minImageWidth: 50, //图片的最小宽度
                    //minImageHeight: 50,//图片的最小高度
                    //maxImageWidth: 1000,//图片的最大宽度
                    //maxImageHeight: 1000,//图片的最大高度
                    //maxFileSize: 0,//单位为kb，如果为0表示不限制文件大小
                    //minFileCount: 0,
                });

                //导入文件上传完成之后的事件
                $("#" + ctrlName).on("fileuploaded", function (event, data, previewId, index) {
                    var response = data.response;
                    var result = response.Success;
                    if (result) {
                        $("#txt_iconUrl").val(response.Data.Path);
                        toastr.info('上传成功');
                        return;
                    }
                    else {
                        toastr.error('上传失败：' + response.Message);
                        return;
                    }
                });
            }
            return oFile;
        };

    </script>
}

